package tnp.modules;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.internal.Nullable;
import com.google.inject.name.Named;

/**
 */
@Singleton
public class XmlSqlSessionFactoryProvider implements Provider<SqlSessionFactory> {
	/**
	 * The SqlSessionFactory reference.
	 */
	private final SqlSessionFactory factory;

	/**
	 */
	@Inject
	public XmlSqlSessionFactoryProvider(@Named("ibatis.classpathResource") final String resource,
			@Named("ibatis.environment") @Nullable final String environment) {
		try {
			Reader reader = Resources.getResourceAsReader(this.getClass().getClassLoader(),
					resource);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			this.factory = builder.build(reader, environment, null);
		} catch (IOException e) {
			throw new RuntimeException("Impossible to read classpath resource '" + resource
					+ "', see nested exceptions", e);
		}
	}

	/**
	 */
	public SqlSessionFactory get() {
		return this.factory;
	}
}
